/*
 * 补发单新建
 * */
var eventId = "";
var btnName = "";
var orderId ="";

$(document).ready(function() {
	var btnName = "";
	// // 日期控件初始化，并且隐藏
	$('#modelBody .datetimepicker-default').datetimepicker();
	eventId = extractEventId();
	btnName = extractBtnText();
	orderId = extractOrdertId();
	$("#orderCode").val($('#hidOrderCodeEvent', window.top.window.getCurrentIframe().contentWindow.document).val());
    $("#tradeCode").val($('#hidTradeCodeEvent', window.top.window.getCurrentIframe().contentWindow.document).val());
    $("#buyerNick").val($('#hidBuyerNickEvent', window.top.window.getCurrentIframe().contentWindow.document).val());
    $("#orderID").val($('#hidOrderIdEvent', window.top.window.getCurrentIframe().contentWindow.document).val());
    //触发失去焦点事件来请求接口

    if(orderId != null && orderId != "" && orderId != undefined){
      $("#orderCode").focus();
      $("#orderID").focus();
    	$("#checkOrderSpan").hide();
//    	setTimeout(function() {
    		$("#orderCode").attr("disabled",true);
//		}, 50);
    	getshiporderCodeList($("#orderID").val());// 发货单编号
	}
	getDictList();// 初始化原因类型
	getHandlePersonList();// 指定处理人
	

	if (btnName != null && btnName != "" && btnName != undefined) {
		// 设置弹出层状态
		setModelType(eventId, btnName);
	}
	
//	$("#newForm").validate({
//        debug:true,
//        errorPlacement: function(error, element)
//        {
//            error.insertAfter(element);
//        }
//    });
});

//设置输入框和下拉框不可用的title属性
function setInputSelectTitle(){
		var length = $("input").length;
		for(var i=0;i<length;i++){
			if($("input")[i].disabled || $("input")[i].readOnly){
				$("input")[i].title = $("input")[i].value;
			}
		}
		var sLength = $("select").length;
		for(var i=0;i<sLength;i++){
			if($("select")[i].disabled){
				var childLength = $("select")[i].children.length;
				for(var j=0;j<childLength;j++){
					if($("select")[i].children[j].value == $("select")[i].value){
						$("select")[i].title = $("select")[i].children[j].text;
						break;
					}
				}
				
			}
		}
}

function setModelType(eventId, btnName) {
	if (btnName == "check") {
//		$('#checkOrderSpan').css('display', 'table-column');
		getEditEvent(eventId)
	} else {

	}
}

/*
 * 修改情况下回显接口
 */
function getEditEvent(eventId) {
	$.ajax({
	    type : "GET",
	    url : "/afterSale/getEvent.action",
	    data : {
		    "eventId" : eventId
	    },
	    contentType : "application/json;charset=utf-8",
	    dataType : "json",
	    async : false,// 同步
	    success : function(data) {
		    if (data.result == "success") {
			    // window.top.window.showModalAlert(data.data);
			    $("#orderCode").val(data.data.orderCode);
			    $("#orderID").val(data.data.orderId);
			    $("#tradeCode").val(data.data.tradeCode);
			    $("#buyerNick").val(data.data.buyerNick);
			    $("#planDealUser").val(data.data.planDealUserId);
			    $("#eventType").val(data.data.eventType);
			    $("#updateTime").val(data.data.expireTime);
			    getshiporderCodeList(data.data.orderId);
	            $("#shiporderCode").val(data.data.stockoutCode);
	            $("#lgstNo").val(data.data.lgstNo);   
			    $("#finishRemark").val(data.data.remark);
		    	$("#checkOrderSpan").hide();
		    	$("#orderCode").attr("disabled",true);
		    	setInputSelectTitle();

		    } else {
			    window.top.window.showModalAlert(data.msg);
		    }
	    },
	    error : function(XMLHttpRequest, textStatus) {
		    if (XMLHttpRequest.status == 500) {
			    var result = eval("(" + XMLHttpRequest.responseText + ")");
			    alert(result.errorObject.errorText);
		    }
	    }
	});
}

// 查询来源单按钮点击
$("#checkOrder").on('click', function() {
	var btnType = "check";
	var iframeSrc2 = "/views/aftersale/event/addAfterSaleEventOrder.html?btnType=" + btnType;
	$("#ifmEventAddOrderDetail").attr("src", iframeSrc2);
	$('#eventCheckWindow').modal();
});

// 指定处理人接口
function getHandlePersonList() {
	console.log(window.top.window.$("#projectSwitch").val());
	var askData = {
		"projectId" : window.top.window.$("#projectSwitch").val(),
	};
	$.ajax({
	    type : "GET",
	    url : "/user/userList.action?length=-1", //传递-1是为了取得所有的用户
	    data : {
		    "formJson" : JSON.stringify(askData)
	    },
	    contentType : "application/json;charset=utf-8",
	    dataType : "json",
	    async : false,// 同步
	    success : function(data) {
		    if (data.result == "success") {
			    $("#planDealUser option").remove();
			    $("#planDealUser").append("<option value=''>请选择</option>");
			    $.each(data.data, function(n, value) {
				    $('#planDealUser').append("<option value='" + value.userId + "'>" + value.userFullname + ":" + value.userAccount + "</option>");
			    });
		    } else {
			    window.top.window.showModalAlert(data.msg);
		    }
	    },
	    error : function(XMLHttpRequest, textStatus) {
		    if (XMLHttpRequest.status == 500) {
			    var result = eval("(" + XMLHttpRequest.responseText + ")");
			    alert(result.errorObject.errorText);
		    }
	    }
	});
}

// 售后原因类型
function getDictList() {
	$.ajax({
	    type : "GET",
	    url : "/dictionary/getParamDictByCode.action",
	    data : {
		    "code" : "AFTER_SALE_TYPE"
	    },
	    contentType : "application/json;charset=utf-8",
	    dataType : "json",
	    async : false,// 同步
	    success : function(data) {
		    if (data.result == "success") {
			    $("#queryEventType option").remove();
			    $("#queryEventType").append("<option value=''>请选择</option>");
			    $("#eventType option").remove();
			    $("#eventType").append("<option value=''>请选择</option>");
			    $.each(data.data, function(n, value) {
				    $('#queryEventType').append("<option value='" + n + "'>" + value + "</option>");
				    $('#eventType').append("<option value='" + n + "'>" + value + "</option>");
			    });
		    } else {
			    window.top.window.showModalAlert(data.msg);
		    }
	    },
	    error : function(XMLHttpRequest, textStatus) {
		    if (XMLHttpRequest.status == 500) {
			    var result = eval("(" + XMLHttpRequest.responseText + ")");
			    alert(result.errorObject.errorText);
		    }
	    }
	});
}

//发货单编号
function getshiporderCodeList(id) {
    console.log("发货单编号 = "+id)
    $.ajax({
        type : "GET",
        url :  "/shiporder/getShiporderListByOrderId.action",
        data : {
            "orderId" : id
        },
        contentType : "application/json;charset=utf-8",
        dataType : "json",
        async : false,// 同步
        success : function(data) {
            if (data.result == "success") {
                $("#shiporderCode option").remove();
                $("#shiporderCode").append("<option value=''>请选择</option>");
                $.each(data.data, function(n, value) {
                    $('#shiporderCode').append("<option value='" + value.shiporderCode + "'>" + value.shiporderCode + "</option>");
                });
            } else {
                window.top.window.showModalAlert(data.msg);
            }
        },
        error : function(XMLHttpRequest, textStatus) {
            if (XMLHttpRequest.status == 500) {
                var result = eval("(" + XMLHttpRequest.responseText + ")");
                alert(result.errorObject.errorText);
            }
        }
    });
}

function saveEvent(context) {
	var loading = window.top.window.getIndexBusyOverlay();
	var nowTime = new Date();
//	var nowDate = mydate.toLocaleString();
	var upTime = new Date($("#updateTime").val());
	//到期时间校验
	if($("#updateTime").val() != ""){
		if(nowTime > upTime){
			loading.remove();
			window.top.window.showModalAlert("到期日期不能小于当前日期！");
			return;
		}
	}
	if(!$("#newForm").valid()) {
        return;
    }
	
	var eventVO = {
	    "eventId" : eventId,
	    "orderId" : $("#orderID").val(),
	    "orderCode" : $("#orderCode").val(),
	    "stockoutCode" : $("#shiporderCode").val(),//发货单单号
	    "lgstNo" : $("#lgstNo").val(),//快递单号
	    "buyerNick" : $("#buyerNick").val(),
	    "eventType" : $("#eventType").val(),
	    "expireTime" : $("#updateTime").val(),// 到期日期
	    "planDealUserId" : $("#planDealUser").val(),// 指定处理人
	    "factDealUser" : "",// 实际处理人
	    "remark" : $("#finishRemark").val(),// 售后事件描述
	    "finishRemark" : ""//
	};

	console.log(eventVO);
	$.ajax({
	    type : "POST",
	    url : "/afterSale/saveEvent.action",
	    data : JSON.stringify(eventVO),
	    contentType : "application/json;charset=utf-8",
	    dataType : "json",
//	    async : false,// 同步
	    beforeSend:function(){
            if(loading) {
            	loading.settext("正在处理中，请稍后...");
            }
        },
	    success : function(data) {
		    if (data.result == "success") {
		    	loading.remove();
			    window.top.window.showScoMessage("ok", data.data);
			    window.top.window.getCurrentIframe().contentWindow.refresh();
			    $('#eventAddWindow', window.top.document).find("#btnEventClose").click();
			    $('#modalEventDetail', window.top.document).find("#btnEventClose").click();
		    } else {
			    window.top.window.showModalAlert(data.msg);
		    }
	    },
	    error : function(XMLHttpRequest, textStatus) {
	    	loading.remove();
		    if (XMLHttpRequest.status == 500) {
			    var result = eval("(" + XMLHttpRequest.responseText + ")");
			    alert(result.errorObject.errorText);
		    }
	    }
	});
}


// 来源单号失去焦点监听
$("#orderCode").blur(function() {   
	var orderCode = $(this).val();
	if (orderCode != "") {
		$.ajax({
		    type : "GET",
		    url : "/order/getOrderInfoByCode.action",
		    data : {
			    "orderCode" : orderCode
		    },
		    contentType : "application/json;charset=utf-8",
		    dataType : "json",
		    async : false,// 同步
		    success : function(data) {
			    if (data.result == "success") {
			    	//orderId
			    	$("#orderID").val(data.data.orderId);
				    $("#tradeCode").val(data.data.tradeCode);
				    $("#buyerNick").val(data.data.buyerNick);
				    getshiporderCodeList(data.data.orderId);// 发货单编号
			    } else {
				    window.top.window.showModalAlert(data.msg);
			    }
		    },
		    error : function(XMLHttpRequest, textStatus) {
			    if (XMLHttpRequest.status == 500) {
				    var result = eval("(" + XMLHttpRequest.responseText + ")");
				    alert(result.errorObject.errorText);
			    }
		    }
		});
	}
	 

});

// 从url中解析按钮名称
function extractBtnText() {
	return extractParam("btnType");
};
// resendId
function extractEventId() {
	return extractParam("eventId");
};
function extractOrdertId() {
	return extractParam("resOrderId");
};
// ===========公共方法==========

// 获取页面参数
function GetArgsFromHref(sHref, sArgName) {
	var args = sHref.split("?");
	var retval = "";

	if (args[0] == sHref) /* 参数为空 */
	{
		return retval; /* 无需做任何处理 */
	}
	var str = args[1];
	args = str.split("&");
	for (var i = 0; i < args.length; i++) {
		str = args[i];
		var arg = str.split("=");
		if (arg.length <= 1)
			continue;
		if (arg[0] == sArgName)
			retval = arg[1];
	}
	return retval;
}

function extractParam(paramName) {
	var returnString = "";
	var str = window.location.search;
	if (!!str) {
		returnString = GetArgsFromHref(str, paramName);
	}
	return returnString;
}
